<template>
  <div>
    <div>
      <el-button class="" @click="exportExcel" size="default" type="primary"
        >导出</el-button
      >
    </div>
    <el-table
      row-class-name="cursor-pointer"
      :data="memberTaskRank"
      @row-click="showMemberFinishDetail"
    >
      <template v-slot:empty>
        <el-empty
          image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
        />
      </template>
      <el-table-column label="" type="index" width="80"></el-table-column>
      <el-table-column prop="name" label="成员"></el-table-column>
      <el-table-column prop="finishCount" label="完成数"></el-table-column>
      <!-- <el-table-column prop="totalCount" label="任务目标"></el-table-column> -->
      <el-table-column prop="percent" label="完成进度">
        <template #default="{ row }">
          <el-progress
            style="width: 80%"
            :text-inside="true"
            :stroke-width="18"
            :percentage="row.percent"
            :color="customColors"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="finishDate"
        label="完成时间"
        :sort-method="sortFinishDate"
      >
        <template #default="{ row }">
          {{ row.percent >= 100 ? TimeYH(row.finishDate) : "-" }}
        </template>
      </el-table-column>
    </el-table>
    <!-- 查看成员任务完成情况弹窗 -->
    <el-dialog
      :title="`${selectedMember.name}-任务详情`"
      v-model="memberTaskDetaildialogVisible"
      width="70%"
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          {{ `${selectedMember.name}-任务详情` }}
        </span>
      </template>
      <QuestionFinishDetail
        v-if="taskType === TaskType.QUESTION"
        :selectedTask="selectedTask"
        :selectedMember="selectedMember"
        :teamjobrelation="questionTaskRelation"
      >
      </QuestionFinishDetail>
      <VideoFinishDetail
        v-else-if="taskType === TaskType.VIDEO"
        :selectedTask="selectedTask"
        :selectedMember="selectedMember"
        :teamjobrelation="videoTaskRelation"
      >
      </VideoFinishDetail>
      <FileFinishDetail
        v-else="taskType === TaskType.FILE"
        :selectedTask="selectedTask"
        :selectedMember="selectedMember"
        :teamjobrelation="fileTaskRelation"
      >
      </FileFinishDetail>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import moment from "moment";
import { computed, onMounted, ref } from "vue";
import { useStore } from "vuex";
import { asyncselectteamjobrelation } from "../../../api";
import { Storekey } from "../../../interface";
import Alymodel from "../../../mysql_interface/model";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { getExceltodownload } from "../../../util/excel";
import { TimeYH } from "../../../util/time";
import { MemberFinishTaskDetail, TaskType } from "@/util/type";
import FileFinishDetail from "./fileFinishDetail.vue";
import QuestionFinishDetail from "./questionFinishDetail.vue";
import VideoFinishDetail from "./videoFinishDetail.vue";

const customColors = [
  { color: "#e83828", percentage: 20 },
  { color: "#f0830ac", percentage: 40 },
  { color: "#82bd1c", percentage: 60 },
  { color: "#1ecbb4", percentage: 70 },
  { color: "#4683fa", percentage: 100 },
];

const props = defineProps<{
  teamUsers: Studycodemodel.Iteamuser[];
  selectedTask: Studycodemodel.Iteamjob;
  questions: Studycodemodel.Iquestion[];
  courses: Alymodel.IMcourse[];
  teamFiles: Studycodemodel.Iteamfile[];
}>();
const store = useStore(Storekey);
const user = computed(() => {
  return store.state.user;
});
const teamid = computed(() => {
  return user.value?.teamid;
});
const teamUsers = computed(() => {
  return props.teamUsers;
});
const questions = computed(() => {
  return props.questions;
});
const courses = computed(() => {
  return props.courses;
});
const teamFiles = computed(() => {
  return props.teamFiles;
});

const selectedTask = computed(() => {
  return props.selectedTask;
});
const taskType = computed(() => {
  return selectedTask.value.type || undefined;
});

onMounted(async () => {
  await showTaskRank();
});

const teamTaskRelation = ref<Studycodemodel.Iteamjobrelation[]>([]);
const taskDetailLoading = ref(false);
// 卡片点击 展开aside
async function showTaskRank() {
  taskDetailLoading.value = true;
  const { rows } = await asyncselectteamjobrelation({
    teamid: teamid.value,
    teamjobid: selectedTask.value.ID,
    _limit: 999999,
  });
  teamTaskRelation.value = rows;
  taskDetailLoading.value = false;
}
// 成员任务完成情况 aside-table
const memberTaskRank = computed(() => {
  let users = new Map<number, MemberFinishTaskDetail>();
  teamTaskRelation.value.forEach((e) => {
    let tmp = users.get(e?.userid);

    if (!tmp) {
      users.set(e?.userid, {
        taskType: selectedTask.value.type,
        taskId: selectedTask.value.ID,
        userId: e.userid,
        name:
          teamUsers.value.find((u) => u.userid === e.userid)?.user?.name ||
          e.userid,
        finishCount: e.state ? 1 : 0,
        totalCount: selectedTask.value.questionnum,
        percent: 0,
        finishDate: undefined,
      });
    }

    if (e.state && tmp) {
      tmp.finishCount++;
      if (tmp.finishDate) {
        let isAfter = moment(e.updatedAt).isAfter(tmp.finishDate);
        tmp.finishDate = isAfter ? (e.updatedAt as Date) : tmp.finishDate;
      } else {
        tmp.finishDate = e.updatedAt as Date;
      }
      let percent = tmp.totalCount
        ? parseInt((tmp.finishCount / tmp.totalCount) * 100)
        : 0;
      tmp.percent = percent > 100 ? 100 : percent;
    }
  });
  return Array.from(users.values())
    .sort((a, b) => {
      return (
        (a.finishDate ? new Date(a.finishDate).getTime() : 0) -
        (b.finishDate ? new Date(b.finishDate).getTime() : 0)
      );
    })
    .sort((a, b) => b.percent - a.percent);
});
// 导出
function exportExcel() {
  const data = [["成员", "完成进度", "完成时间"]];
  for (let v of memberTaskRank.value.filter((e) => e.finishCount)) {
    const n = [
      v?.name || "",
      v.percent + "%",
      v.percent >= 100 ? new Date(v.finishDate).toLocaleString() : "",
    ];
    data.push(n);
  }
  getExceltodownload(data, String(selectedTask.value.name));
}
// TODO　完成时间排序 后 前
function sortFinishDate(a, b) {
  const tmpA = new Date(a.finishDate).getTime();
  const tmpB = new Date(b.finishDate).getTime();
  return moment(tmpB).isAfter(tmpA) ? 1 : 0;
}

// 某个任务某个成员的具体完成情况
const selectedMember = ref<MemberFinishTaskDetail>({}); // 概况
const memberTaskRelation = ref<Studycodemodel.Iteamjobrelation[]>([]); // 详情
const questionTaskRelation = ref<Studycodemodel.Iteamjobrelation[]>([]); // question
const videoTaskRelation = ref<Studycodemodel.Iteamjobrelation[]>([]); // video
const fileTaskRelation = ref<Studycodemodel.Iteamjobrelation[]>([]); // file
const memberTaskDetaildialogVisible = ref(false);
function showMemberFinishDetail(row: MemberFinishTaskDetail) {
  // 学生不能查看具体情况
  if (!user.value?.isAdmin) {
    return;
  }
  selectedMember.value = row;
  memberTaskDetaildialogVisible.value = true;
  const selectedUid = row.userId;
  // 从 selectteamjobrelation 筛选指定成员
  memberTaskRelation.value = teamTaskRelation.value.filter(
    (e) => e.userid === selectedUid
  );
  if (taskType.value === TaskType.QUESTION) {
    // 补全任务中的题目名称
    questionTaskRelation.value = memberTaskRelation.value.map((f) => {
      const q = questions.value.find((t) => t.ID === f.questionid);
      return { ...f, qName: q.name };
    });
  } else if (taskType.value === TaskType.VIDEO) {
    videoTaskRelation.value =
      memberTaskRelation.value.map((f) => {
        const { courseid, watchvideoid, catebagid, state } = f;
        // 所有资源中筛选本任务的
        const course = courses.value.find((t) => t.ID === courseid);
        const jobquestion = selectedTask.value?.jobquestion.find(
          (t) => t.courseid === courseid
        );
        return {
          courseid,
          name: course?.name,
          time:
            watchvideoid
              ?.map((f) => f.time)
              .reduce((a = 0, b = 0) => a + b, 0) || 0,
          catebagid,
          state,
          paixu: jobquestion?.index || 0,
        };
      }) || [];
    videoTaskRelation.value.sort((a, b) => a.paixu - b.paixu);
  } else if (taskType.value === TaskType.FILE) {
    fileTaskRelation.value =
      memberTaskRelation.value.map((f) => {
        const { teamfileid, state } = f;
        const course = teamFiles.value.find((t) => t.ID === teamfileid);
        return {
          teamfileid,
          name: course?.name,
          state,
        };
      }) || [];
  }
}
</script>

<style scoped></style>
